package com.gtc.zsk.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.gtc.zsk.common.ErrorCode;
import com.gtc.zsk.common.ResultUtils;
import com.gtc.zsk.constant.CommonConstant;
import com.gtc.zsk.exception.BusinessException;
import com.gtc.zsk.exception.ThrowUtils;
import com.gtc.zsk.mapper.QuestionApplyMapper;
import com.gtc.zsk.model.dto.question.QuestionQueryRequest;
import com.gtc.zsk.model.dto.questionApply.QuestionApplyPassRequest;
import com.gtc.zsk.model.dto.questionApply.QuestionApplyQueryRequest;
import com.gtc.zsk.model.entity.*;
import com.gtc.zsk.model.enums.QuestionApplyStatusEnum;
import com.gtc.zsk.service.*;
import com.gtc.zsk.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.gtc.zsk.constant.QuestionBankConstant.defaultQuestionBankAvatar;

/**
* @author 16153
* @description 针对表【question_apply(题目)】的数据库操作Service实现
* @createDate 2025-01-09 16:30:55
*/
@Service
public class QuestionApplyServiceImpl extends ServiceImpl<QuestionApplyMapper, QuestionApply>
    implements QuestionApplyService {

    @Resource
    private UserService userService;

    @Resource
    private QuestionBankService questionBankService;

    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionBankQuestionService questionBankQuestionService;


    @Override
    public void validQuestionApply(QuestionApply questionApply, boolean add) {
        ThrowUtils.throwIf(questionApply == null, ErrorCode.PARAMS_ERROR);
        // todo 从对象中取值
        String questionTitle = questionApply.getQuestionTitle();
        String content = questionApply.getContent();
        String picture = questionApply.getPicture();
        List<String> tagList = JSONUtil.toList(JSONUtil.parseArray(questionApply.getTags()), String.class);
        String questionBankTitle = questionApply.getQuestionBankTitle();
        List<Long> questionBankIds = JSONUtil.toList(JSONUtil.parseArray(questionApply.getQuestionBankIds()), Long.class);
        String description = questionApply.getDescription();
        ThrowUtils.throwIf(StringUtils.isNotBlank(questionBankTitle) && CollUtil.isNotEmpty(questionBankIds), ErrorCode.PARAMS_ERROR, "参数错误喽！别攻击我！");
        // 创建数据时，参数不能为空
        if (add) {
            // todo 补充校验规则
            ThrowUtils.throwIf(StringUtils.isBlank(questionTitle), ErrorCode.PARAMS_ERROR, "题目标题不能为空！");
            ThrowUtils.throwIf(CollUtil.isEmpty(questionBankIds) && StringUtils.isBlank(questionBankTitle), ErrorCode.PARAMS_ERROR, "请选择已有题库或自定义题库！");
        }
        // 修改数据时，有参数则校验
        // todo 补充校验规则
        if (CollUtil.isNotEmpty(questionBankIds)){
            List<QuestionBank> questionBanks = questionBankService.listByIds(questionBankIds);
            ThrowUtils.throwIf(questionBanks == null || CollUtil.isEmpty(questionBanks) || questionBanks.size() != questionBankIds.size() , ErrorCode.NOT_FOUND_ERROR, "题库不存在！");
        }
        if (StringUtils.isNotBlank(questionTitle)) {
            ThrowUtils.throwIf(questionTitle.length() > 80, ErrorCode.PARAMS_ERROR, "标题过长！");
        }
        if (StringUtils.isNotBlank(questionBankTitle)) {
            ThrowUtils.throwIf(questionTitle.length() > 80, ErrorCode.PARAMS_ERROR, "标题过长！");
        }
        if (StringUtils.isNotBlank(content)) {
            ThrowUtils.throwIf(content.length() > 10240, ErrorCode.PARAMS_ERROR, "内容过长！");
        }
        if (StringUtils.isNotBlank(description)) {
            ThrowUtils.throwIf(description.length() > 100, ErrorCode.PARAMS_ERROR, "题库描述过长！");
        }
        if (CollUtil.isNotEmpty(tagList)){
            ThrowUtils.throwIf(tagList.size() > 6, ErrorCode.PARAMS_ERROR, "添加标签过多！");
        }
        if (StringUtils.isBlank(picture)){
            questionApply.setPicture(defaultQuestionBankAvatar);
        }
    }


    @Override
    public QueryWrapper<QuestionApply> getQueryWrapper(QuestionApplyQueryRequest questionApplyQueryRequest) {
        QueryWrapper<QuestionApply> queryWrapper = new QueryWrapper<>();
        if (questionApplyQueryRequest == null) {
            return queryWrapper;
        }

        // todo 从对象中取值
        Long id = questionApplyQueryRequest.getId();
//        Long notId = questionQueryRequest.getNotId();
        String searchText = questionApplyQueryRequest.getSearchText();
        String questionTitle = questionApplyQueryRequest.getQuestionTitle();
        String content = questionApplyQueryRequest.getContent();
        List<String> tagList = questionApplyQueryRequest.getTags();
        String description = questionApplyQueryRequest.getDescription();
        String questionBankTitle = questionApplyQueryRequest.getQuestionBankTitle();
        String answer = questionApplyQueryRequest.getAnswer();
        Integer status = questionApplyQueryRequest.getStatus();
        String reason = questionApplyQueryRequest.getReason();
        String sortField = questionApplyQueryRequest.getSortField();
        String sortOrder = questionApplyQueryRequest.getSortOrder();
        Long userId = questionApplyQueryRequest.getUserId();
        List<Long> questionBankIds = questionApplyQueryRequest.getQuestionBankIds();

        // todo 补充需要的查询条件
        // 从多字段中搜索
        if (StringUtils.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("title", searchText).or().like("content", searchText));
        }
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(questionTitle), "questionTitle", questionTitle);
        queryWrapper.like(StringUtils.isNotBlank(questionBankTitle), "questionBankTitle", questionBankTitle);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        queryWrapper.like(StringUtils.isNotBlank(answer), "answer", answer);
        queryWrapper.like(StringUtils.isNotBlank(description), "description", description);
        queryWrapper.like(StringUtils.isNotBlank(reason), "reason", reason);
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tagList)) {
            for (String tag : tagList) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        if (CollUtil.isNotEmpty(questionBankIds)) {
            for (Long questionBankId : questionBankIds) {
                queryWrapper.like("questionBankIds", questionBankId);
            }
        }
        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }


    public Page<QuestionApply> listQuestionApplyByPage(QuestionApplyQueryRequest questionApplyQueryRequest) {
        long current = questionApplyQueryRequest.getCurrent();
        long size = questionApplyQueryRequest.getPageSize();
        QueryWrapper<QuestionApply> queryWrapper = this.getQueryWrapper(questionApplyQueryRequest);
        // 查询数据库
        Page<QuestionApply> questionPage = this.page(new Page<>(current, size), queryWrapper);
        return questionPage;
    }

    @Transactional
    public Long executeQuestionApplyNotAddQuestionBank(QuestionApplyPassRequest questionApplyPassRequest){
        String answer = questionApplyPassRequest.getAnswer();
        String content = questionApplyPassRequest.getContent();
        List<Long> questionBankIds = questionApplyPassRequest.getQuestionBankIds();
        String questionTitle = questionApplyPassRequest.getQuestionTitle();
        List<String> tags = questionApplyPassRequest.getTags();
        Long userId = questionApplyPassRequest.getUserId();

        Question question = new Question();
        question.setAnswer(answer);
        question.setContent(content);
        question.setTitle(questionTitle);
        question.setUserId(userId);
        //手动转换
        if (tags != null)
            question.setTags(JSONUtil.toJsonStr(tags));
        // 写入数据库
        boolean questionResult = questionService.save(question);
        ThrowUtils.throwIf(!questionResult, ErrorCode.OPERATION_ERROR, "题目录入数据库错误！");
        // 返回新写入的数据 id
        long newQuestionId = question.getId();

        ThrowUtils.throwIf(CollUtil.isEmpty(questionBankIds), ErrorCode.PARAMS_ERROR, "所属题库不能为空！");
        for (Long questionBankId : questionBankIds) {
            QuestionBankQuestion questionBankQuestion = new QuestionBankQuestion();
            questionBankQuestion.setQuestionId(newQuestionId);
            if (questionBankId != null){
                QuestionBank questionBank = questionBankService.getById(questionBankId);
                ThrowUtils.throwIf(questionBank == null, ErrorCode.NOT_FOUND_ERROR, "题库不存在！");
            }
            questionBankQuestion.setQuestionBankId(questionBankId);
            questionBankQuestion.setUserId(userId);
            boolean questionBankQuestionResult = questionBankQuestionService.save(questionBankQuestion);
            ThrowUtils.throwIf(!questionBankQuestionResult, ErrorCode.OPERATION_ERROR, "插入题库出现错误！");
        }
        return newQuestionId;
    }

    @Transactional
    public Long executeQuestionApplyAddQuestionBank(QuestionApplyPassRequest questionApplyPassRequest){
        String answer = questionApplyPassRequest.getAnswer();
        String content = questionApplyPassRequest.getContent();
        String description = questionApplyPassRequest.getDescription();
        String picture = questionApplyPassRequest.getPicture();
        String questionBankTitle = questionApplyPassRequest.getQuestionBankTitle();
        String questionTitle = questionApplyPassRequest.getQuestionTitle();
        List<String> tags = questionApplyPassRequest.getTags();
        Long userId = questionApplyPassRequest.getUserId();

        Question question = new Question();
        question.setAnswer(answer);
        question.setContent(content);
        question.setTitle(questionTitle);
        question.setUserId(userId);
        //手动转换
        if (tags != null)
            question.setTags(JSONUtil.toJsonStr(tags));
        // 写入数据库
        boolean questionResult = questionService.save(question);
        ThrowUtils.throwIf(!questionResult, ErrorCode.OPERATION_ERROR, "题目录入数据库错误！");
        // 返回新写入的数据 id
        long newQuestionId = question.getId();
        QuestionBank questionBank = new QuestionBank();
        questionBank.setTitle(questionBankTitle);
        questionBank.setPicture(picture);
        questionBank.setDescription(description);
        questionBank.setUserId(userId);
        // 数据校验
        questionBankService.validQuestionBank(questionBank, true);
        // 写入数据库
        boolean questionBankResult = questionBankService.save(questionBank);
        ThrowUtils.throwIf(!questionBankResult, ErrorCode.OPERATION_ERROR, "创建知识库失败！");
        // todo 在此处将实体类和 DTO 进行转换
        QuestionBankQuestion questionBankQuestion = new QuestionBankQuestion();
        questionBankQuestion.setQuestionBankId(questionBank.getId());
        questionBankQuestion.setQuestionId(newQuestionId);
        questionBankQuestion.setUserId(userId);
        // 写入数据库
        boolean questionBankQuestionResult = questionBankQuestionService.save(questionBankQuestion);
        ThrowUtils.throwIf(!questionBankQuestionResult, ErrorCode.OPERATION_ERROR, "插入题库出现错误！");
        return newQuestionId;
    }

    @Transactional
    @Override
    public void passQuestionApply(QuestionApplyPassRequest questionApplyPassRequest, HttpServletRequest request) {
        if (questionApplyPassRequest == null || questionApplyPassRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long questionId = null;
        User user = userService.getLoginUser(request);
        long id = questionApplyPassRequest.getId();
        String reason = questionApplyPassRequest.getReason();
        List<Long> questionBankIds = questionApplyPassRequest.getQuestionBankIds();
        String questionBankTitle = questionApplyPassRequest.getQuestionBankTitle();
        QuestionApplyServiceImpl questionApplyService = (QuestionApplyServiceImpl) AopContext.currentProxy();
        if (CollUtil.isNotEmpty(questionBankIds) && StringUtils.isBlank(questionBankTitle)){
            questionId = questionApplyService.executeQuestionApplyNotAddQuestionBank(questionApplyPassRequest);
        }
        if (CollUtil.isEmpty(questionBankIds) && StringUtils.isNotBlank(questionBankTitle)){
            questionId = questionApplyService.executeQuestionApplyAddQuestionBank(questionApplyPassRequest);
        }
        // 判断是否存在
        QuestionApply oldQuestionApply = questionApplyService.getById(id);
        ThrowUtils.throwIf(oldQuestionApply == null, ErrorCode.NOT_FOUND_ERROR);
        QuestionApply questionApply = new QuestionApply();
        questionApply.setId(id);
        questionApply.setReviewUserId(user.getId());
        questionApply.setReviewUserName(user.getUserName());
        questionApply.setQuestionId(questionId);
        if (reason != null)
            questionApply.setReason(reason);
        questionApply.setStatus(QuestionApplyStatusEnum.PASSED.getValue());
        // 操作数据库
        boolean result = questionApplyService.updateById(questionApply);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }


}




